package com.yongninger.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import android.content.Context;
import android.os.Environment;

public class ExportDoc {
	private String destFile = "";
	private String srcFile = "systemyne.doc";
	private String fileName;
	private String dir;
	public ExportDoc(){}
	public ExportDoc(String fileName){
		this.fileName = fileName;
	}
	//创建文件夹及文件 
	 
    public void CreateText() throws IOException { 
    	dir = Environment.getExternalStorageDirectory() + "/yongniner";
        File file = new File(dir); 
 
        if (!file.exists()) { 
            file.mkdirs(); 
        } 
        File dir1 = new File(dir + "/" + fileName); 
        if (!dir1.exists()) { 
          //在指定的文件夹中创建文件 
          dir1.createNewFile(); 
        } 
    } 

	
	
	public boolean export(Context context, Map<String, String> map) {
		boolean temp = true;
		// #####################根据自定义内容导出Word文档#################################################
		StringBuffer fileCon = new StringBuffer();
		try {
			CreateText();
			destFile = dir + "/" + fileName;
			/*destFile = File.createTempFile("yongninger", ".doc",
					Environment.getExternalStorageDirectory())
					.getAbsolutePath();*/
		} catch (Exception e1) {
			temp = false;
		}
		fileCon.append("               张大炮            男              317258963215223\n"
				+ "2011     09        2013     07       3\n"
				+ "    二炮研究              成人\n"
				+ "2013000001                             2013     07     08");
		fileCon.append("\n\r\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

		exportDoc(destFile, fileCon.toString());

		// 注意biyezheng_moban.doc文档位置,此例中为应用根目录 biyezheng_moban systemyne
		HWPFDocument document = replaceDoc(context, srcFile, map);
		ByteArrayOutputStream ostream = new ByteArrayOutputStream();
		try {
			document.write(ostream);
			// 输出word文件
			OutputStream outs = new FileOutputStream(destFile);
			outs.write(ostream.toByteArray());
			outs.close();
		} catch (Exception e) {
			temp = false;
		}
		return temp;
	}

	/**
	 * 
	 * @param destFile
	 * @param fileCon
	 */
	public void exportDoc(String destFile, String fileCon) {
		try {
			// doc content
			ByteArrayInputStream bais = new ByteArrayInputStream(
					fileCon.getBytes());
			POIFSFileSystem fs = new POIFSFileSystem();
			DirectoryEntry directory = fs.getRoot();
			directory.createDocument("WordDocument", bais);
			FileOutputStream ostream = new FileOutputStream(destFile);
			fs.writeFilesystem(ostream);
			bais.close();
			ostream.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取word模板并替换变量
	 * 
	 * @param srcPath
	 * @param map
	 * @return
	 */
	public HWPFDocument replaceDoc(Context context,String srcPath, Map<String, String> map) {
    	 HWPFDocument doc = null;
    	 try {
             // 读取word模板
            // FileInputStream fis = new FileInputStream();
        	 InputStream is = context.getAssets()
   					.open(srcPath);
             doc = new HWPFDocument(is);
             // 读取word文本内容
             Range bodyRange = doc.getRange();
             // 替换文本内容
             for (Map.Entry<String, String> entry : map.entrySet()) {
            	 String value = entry.getValue();
            	 if(entry.getKey().indexOf("c") == 0){
            		 int j = 4-value.length();
                	 //补上空格
                	 for (int i = 0; i < j; i++) {
                		 value += " ";
    				}
            	 }else if(entry.getKey().indexOf("user") == 0){
            		 int j = 11-value.length();
                	 //补上空格
                	 for (int i = 0; i < j; i++) {
                		 value += " ";
    				}
            	 }
                 bodyRange.replaceText("{" + entry.getKey() + "}", value);
             }
             is.close();
         } catch (Exception e) {
             String ea = e.getMessage();
             System.out.println(ea);
         }
         return doc;
     }
}